package com.unohacha.qqj.fzdr.main.sends;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.qpg.superhttp.SuperHttp;
import com.qpg.superhttp.callback.SimpleCallBack;
import com.qpg.superhttp.request.UploadRequest;
import com.qpg.widget.common.ToastUtil;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.imgpicker.FabricImagePickerAdapter;
import com.unohacha.qqj.fzdr.bean.BaseBean;
import com.unohacha.qqj.fzdr.bean.BooleanModel;
import com.unohacha.qqj.fzdr.bean.ImgBean;
import com.unohacha.qqj.fzdr.bean.PostingModle;
import com.unohacha.qqj.fzdr.bean.homebean.HomeAppSellerAreaBean;
import com.unohacha.qqj.fzdr.util.GlideImageLoaderForPicker;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.TimeUtils;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.mylibrary.base.BaseActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 商家讨论-- 主题发布
 */
public class SendNoteActivity extends BaseActivity implements FabricImagePickerAdapter.OnRecyclerViewItemClickListener {

    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.home1_title)
    LinearLayout home1Title;
    @BindView(R.id.company_type_tv)
    TextView companyTypeTv;
    @BindView(R.id.theme_type_rl)
    RelativeLayout themeTypeRl;
    @BindView(R.id.theme_title)
    EditText themeTitle;
    @BindView(R.id.theme_content)
    EditText themeContent;
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    @BindView(R.id.send_btn)
    Button sendBtn;

    private FabricImagePickerAdapter imagePickerAdapter;
    public static ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private int maxImgCount = 9; //允许选择图片最大数
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private OptionsPickerView pvReleaseType;
    private List<HomeAppSellerAreaBean.DataBean> titleList;
    HashMap<String, String> map;
    private int releaseTypeId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_send_note;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setText("发布主题");
        commonRightImage.setVisibility(View.VISIBLE);
        commonRightText.setVisibility(View.GONE);
        commonRightImage.setImageResource(R.drawable.ic_all_comment);
        map = new HashMap<>();
        initImagePicker();
        selImageList = new ArrayList<>();
        imagePickerAdapter = new FabricImagePickerAdapter(this, selImageList, maxImgCount);
        imagePickerAdapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(imagePickerAdapter);

        initOptions();
        
        titleList = (List<HomeAppSellerAreaBean.DataBean>) getIntent().getSerializableExtra("titleList");
        ArrayList<String> list = new ArrayList<>();
        
        for(int i=0;i<titleList.size();i++) {
            list.add(titleList.get(i).getName());
        }
        pvReleaseType.setPicker(list);
    }
    
    private void initOptions(){
        pvReleaseType = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                companyTypeTv.setText(titleList.get(options1).getName());
                releaseTypeId = titleList.get(options1).getId();

            }
        }).setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.RED)
                .setSubmitText("完成")
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoaderForPicker());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }
    
    @OnClick({R.id.common_back, R.id.send_btn,R.id.theme_type_rl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                finish();
                break;
            case R.id.theme_type_rl:
                pvReleaseType.show();
                break;
            case R.id.send_btn:
                if(TextUtils.isEmpty(themeTitle.getText().toString())){
                    ToastUtils.showT("请输入标题");
                }else if(TextUtils.isEmpty(themeContent.getText().toString())){
                    ToastUtils.showT("请输入内容");
                }else if(releaseTypeId == 0){
                    ToastUtils.showT("请输入发布类型");
                }else {
                    businessRelease();
                }
                break;
        }
    }

    //发帖
    private void businessRelease(){

        HashMap<String,String> parmas=new HashMap<>();
        parmas.put("token", Prefer.getInstance().getToken());
        parmas.put("type","1");
        UploadRequest uploadRequest= SuperHttp.upload("api/filepic/filePic");
        if(images!=null){
            for (int i=0;i<images.size();i++){
                uploadRequest.addImageFile("file"+i,new File(images.get(i).path));
            }
        }else {
            ToastUtil.showCustomToast("请选择图片");
            return;
        }

        uploadRequest.addParams(parmas);

        showLoading();
        uploadRequest.request(new SimpleCallBack<BaseBean<List<ImgBean>>>() {
            @Override
            public void onFail(int errCode, String errMsg) {
                hideLoading();
            }

            @Override
            public void onSuccess(BaseBean<List<ImgBean>> data) {
                StringBuilder stringBuilder=new StringBuilder();
                for (int i=0;i<data.getData().size();i++){
                    stringBuilder.append(data.getData().get(i).getId()+",");
                }
                map.clear();
                map.put("content_img",stringBuilder.toString());

                map.put("token",Prefer.getInstance().getToken());
                map.put("app_cate_id",releaseTypeId+"");
                map.put("title",themeTitle.getText().toString());
                map.put("content",themeContent.getText().toString());
                map.put("area_id",","+12685+",");
                Log.d("adsfa",Prefer.getInstance().getToken()+" "+releaseTypeId+" "+stringBuilder.toString());
                SuperHttp.post("api/mycenter/appBusinessForumAdd")
                        .addParams(map)
                        .request(new SimpleCallBack<PostingModle>() {
                            @Override
                            public void onSuccess(PostingModle data) {
                                ToastUtils.showT(data.getMessage());
                                //目前只请求下支付接口，因为发布是要付费的
                                finish();

                            }

                            @Override
                            public void onFail(int errCode, String errMsg) {
                                ToastUtils.showT(errMsg);
                            }
                        });
                hideLoading();
            }
        });
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent1 = new Intent(SendNoteActivity.this, ImageGridActivity.class);
                startActivityForResult(intent1, REQUEST_CODE_SELECT);

                break;
//            default:
//                //打开预览
//                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
//                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
//                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
//                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
//                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
//                break;
        }
    }

    ArrayList<ImageItem> images = null;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    imagePickerAdapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    imagePickerAdapter.setImages(selImageList);
                }
            }
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    
}
